<?php
	define('LOGIN_SERVICE',true);
	require_once './LoginService.class.php';	
	require_once '../Classes/User.class.php';
	require_once '../Tool/Common/PrepareInput.php';
	//Session start
	session_start();
	
	//Retrieve captcha
	//$captcha=$_POST['Captcha'];

	//Check verificaiton code
	//if($captcha != $_SESSION['captcha']){
		//header('Location: ../firstphp.php?errno=1');
		//exit();
	//}
	if(!empty($_POST['username']) && !empty($_POST['password'])){
		//Retrieve usernanme
		$username=prepareInput($_POST['username']);
		if (!preg_match("/^[0-9A-Za-z ]*$/",$username)){
			header('Location: ../Index.php?errno=2');
			exit();
		}
		//Retrieve password
		$password=$_POST['password'];
		if (!preg_match("/^[0-9A-Za-z\S]*$/",$password)){
			header('Location: ../Index.php?errno=3');
			exit();
		}	
	}
	
	/*if(!empty($_POST['Keep'])){
		//store username&password into cookie
		setCookie("username",$username,time()+7*24*3600);
		setCookie("password",$password,time()+1*24*3600);
	}else{
		if(!empty($_COOKIE['username']) && !empty($_COOKIE['password'])){
			setCookie("username",$username,time()-100);
			setCookie("password",$password,time()-100);
		}
	}*/

	//Create a loginService object 
	$loginService = new LoginService();
	
	//Create a user object 
	$user = new User();
	
	//User authentication
	$user=$loginService->checkUser($username, $password);
	
	if(!empty($user)){
		//Success
		//Store usertype
		$_SESSION['userType']=$user->getUserType();
		$_SESSION['username']=$user->getUserName();
		$_SESSION["centreID"]=$user->getCentreID();
		
		//Store centre name
		$centreName=$loginService->RetrieveCentreNameByUsername($user->getUserName());
		if(!empty($centreName)){
			$_SESSION["centreName"]=$centreName;
		}else{
			$_SESSION["centreName"]=NULL;
		}
		//Direct to another page
		if($_SESSION['userType']!="Centre Manager"){
			header('Location: ../AttendanceHome.php');
			exit();	
		}else{
			header('Location: ../ViewAttendanceRecord.php');
			exit();		
		}
		
	}else{
		//Fail
		header('Location: ../Index.php?errno=1');
		exit();
	}
?>